package com.peng.community.service.impl;

import com.peng.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService {

    @Autowired
    RedisTemplate redisTemplate;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    //增加一条访问记录
    public void recordUV(String ip) {
        String uvKey = RedisKeyUtil.getUVKey(sdf.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey,ip);
    }

    //查询一个区间类的访问人员数量
    //先得到这个区间所有的日期集合，再利用HLL进行合并
    public long calculateUV(Date start, Date end) {
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) { //从start到end的每一天
            keyList.add(RedisKeyUtil.getUVKey(sdf.format(calendar.getTime())));
            calendar.add(Calendar.DATE,1); //加一天
        }

        //合并的KEY
        String union = RedisKeyUtil.getUVKey(sdf.format(start), sdf.format(end));
        redisTemplate.opsForHyperLogLog().union(union,keyList.toArray());

        return redisTemplate.opsForHyperLogLog().size(union);
    }

    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(sdf.format(new Date()));
        redisTemplate.opsForValue().setBit(dauKey, userId,true);
    }

    //统计一段时间内的访问总数
    //一个用户只需在这些天访问过一次，就算访问；因此所有天数的同一个用户也只算一次，即或
    public long calculateDAU(Date start, Date end) {
        List<byte[]> keyList = new ArrayList<>(); //需要byte[]的key
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) { //从start到end的每一天
            keyList.add(RedisKeyUtil.getDAUKey(sdf.format(calendar.getTime())).getBytes());
            calendar.add(Calendar.DATE,1); //加一天
        }

        return (long)redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] dauKey = RedisKeyUtil.getDAUKey(sdf.format(start), sdf.format(end)).getBytes();
                connection.bitOp(RedisStringCommands.BitOperation.OR, dauKey, keyList.toArray(new byte[0][0]));
                return connection.bitCount(dauKey);
            }
        });
    }

}
